package com.xindaoapp.happypet.activity;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.XDHttpClient;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.PushMessage;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.xdConfig;

/**
 * 推送设置页面
 * 
 * @author Stone
 * 
 */
public class PushMessageActivity extends UMBaseActivity implements OnClickListener {
    @ViewInject(R.id.message_cancel)
    private ImageView message_cancel;
    @ViewInject(R.id.setting_isreply)
    private CheckBox setting_isreply;
    @ViewInject(R.id.setting_ispm)
    private CheckBox setting_ispm;
    @ViewInject(R.id.setting_isat)
    private CheckBox setting_isat;
    @ViewInject(R.id.setting_isfollow)
    private CheckBox setting_isfollow;
    @ViewInject(R.id.setting_issystem)
    private CheckBox setting_issystem;
    @ViewInject(R.id.setting_isaudio)
    private CheckBox setting_isaudio;

    private SharedPreferences sp;
    private PushMessage pushMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pushmessage);
        ViewUtils.inject(this);
        sp = getSharedPreferences("userconfig", MODE_PRIVATE);
        initClick();
        initcheck();
        initdate();
    }

    /**
     * 初始化选择框
     */
    private void initcheck() {
        setting_isreply.setChecked(sp.getBoolean("isreply", true));
        setting_ispm.setChecked(sp.getBoolean("ispm", true));
        setting_isat.setChecked(sp.getBoolean("isat", true));
        setting_isfollow.setChecked(sp.getBoolean("isfollow", true));
        setting_issystem.setChecked(sp.getBoolean("issystem", true));
        setting_isaudio.setChecked(sp.getBoolean("isaudio", true));
    }

    /**
     * 获取网络数据
     */
    private void initdate() {
        getAssetsData(xdConfig.PUSHMESSAGE);
    }

    // 获取网络数据
    private void getAssetsData(String url) {
        RequestParams params = new RequestParams();
        params.put("", "");
        XDHttpClient.post(url, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                super.onSuccess(statusCode, content);
                JSONObject jsonObj;
                try {
                    jsonObj = new JSONObject(content);
                    JSONObject result = jsonObj.getJSONObject("info");
                    pushMessage = new PushMessage();
                    pushMessage.setUid(Integer.parseInt(result.getString("uid")));
                    pushMessage.setIsreply(Integer.parseInt(result.getString("isreply")));
                    pushMessage.setIsfollow(Integer.parseInt(result.getString("isfollow")));
                    pushMessage.setIssystem(Integer.parseInt(result.getString("issystem")));
                    pushMessage.setIspm(Integer.parseInt(result.getString("ispm")));
                    pushMessage.setIsat(Integer.parseInt(result.getString("isat")));
                    pushMessage.setIsaudio(Integer.parseInt(result.getString("isaudio")));
                    Editor editor = sp.edit();
                    if (pushMessage.getIsreply() == 0) {
                        editor.putBoolean("isreply", false);
                        setting_isreply.setChecked(false);
                    } else {
                        editor.putBoolean("isreply", true);
                        setting_isreply.setChecked(true);
                    }
                    if (pushMessage.getIsfollow() == 0) {
                        editor.putBoolean("isfollow", false);
                        setting_isfollow.setChecked(false);
                    } else {
                        editor.putBoolean("isfollow", true);
                        setting_isfollow.setChecked(true);
                    }
                    if (pushMessage.getIssystem() == 0) {
                        editor.putBoolean("issystem", false);
                        setting_issystem.setChecked(false);
                    } else {
                        editor.putBoolean("issystem", true);
                        setting_issystem.setChecked(true);
                    }
                    if (pushMessage.getIspm() == 0) {
                        editor.putBoolean("ispm", false);
                        setting_ispm.setChecked(false);
                    } else {
                        editor.putBoolean("ispm", true);
                        setting_ispm.setChecked(true);
                    }
                    if (pushMessage.getIsat() == 0) {
                        editor.putBoolean("isat", false);
                        setting_isat.setChecked(false);
                    } else {
                        editor.putBoolean("isat", true);
                        setting_isat.setChecked(true);
                    }

                    if (pushMessage.getIsaudio() == 0) {
                        editor.putBoolean("isaudio", false);
                        setting_isaudio.setChecked(false);
                    } else {
                        editor.putBoolean("isaudio", true);
                        setting_isaudio.setChecked(true);
                    }

                    editor.commit();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
            }
        });
    }

    private void initClick() {
        findViewById(R.id.mark_all).setOnClickListener(this);
        message_cancel.setOnClickListener(this);
        setting_isreply.setOnClickListener(this);
        setting_ispm.setOnClickListener(this);
        setting_isfollow.setOnClickListener(this);
        setting_issystem.setOnClickListener(this);
        setting_isaudio.setOnClickListener(this);
        setting_isreply.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sp.edit().putBoolean("isreply", isChecked).commit();
                postSetting();
            }
        });
        setting_ispm.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sp.edit().putBoolean("ispm", isChecked).commit();
                postSetting();
            }
        });
        setting_isat.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sp.edit().putBoolean("isat", isChecked).commit();
                postSetting();
            }
        });
        setting_isfollow.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sp.edit().putBoolean("isfollow", isChecked).commit();
                postSetting();
            }
        });
        setting_issystem.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sp.edit().putBoolean("issystem", isChecked).commit();
                postSetting();
            }
        });
        setting_isaudio.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sp.edit().putBoolean("isaudio", isChecked).commit();
                postSetting();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.message_cancel:
                finish();
                break;
            case R.id.mark_all:
                markAll();
                break;
            default:
                break;
        }
    }

    /**
     * 标记全部
     */
    private void markAll() {

        if (!Constants.NoticeLabel.sHasNewMessageNotice) {
            Toast.makeText(PushMessageActivity.this, "没有未读消息！", Toast.LENGTH_SHORT).show();
            return;
        }

        AlertDialog dialog =
                new AlertDialog.Builder(this).setTitle("提醒").setMessage("确认将消息标记为全部已读")
                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                HappyPetApplication.get().getMoccaApi()
                                        .noticeCleanAllNew(new IRequest<Boolean>() {

                                            @Override
                                            public void request(Boolean t) {
                                                if (t) {
                                                    Constants.NoticeLabel.sHasNewMessageNotice =
                                                            false;
                                                    PushMessageActivity.this
                                                            .sendBroadcast(new Intent(
                                                                    Constants.ACTION_RECEIVED_NOTICE));
                                                    PushMessageActivity.this.finish();
                                                    Toast.makeText(PushMessageActivity.this,
                                                            "已全部标记为已读！", Toast.LENGTH_SHORT).show();
                                                } else {
                                                    Toast.makeText(PushMessageActivity.this,
                                                            "清除失败！", Toast.LENGTH_SHORT).show();
                                                }
                                            }
                                        });
                            }
                        }).setPositiveButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {}
                        }).create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    private void postSetting() {
        RequestParams params = new RequestParams();
        params.put("isreply", boolean2int(sp.getBoolean("isreply", true)));
        params.put("ispm", boolean2int(sp.getBoolean("ispm", true)));
        params.put("isat", boolean2int(sp.getBoolean("isat", true)));
        params.put("isfollow", boolean2int(sp.getBoolean("isfollow", true)));
        params.put("issystem", boolean2int(sp.getBoolean("issystem", true)));
        params.put("isaudio", boolean2int(sp.getBoolean("isaudio", true)));
        XDHttpClient.post(xdConfig.SETMESSAGE, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                super.onSuccess(statusCode, content);
                Intent intent = new Intent(Constants.ACTION_AUDIO_SETTING_CHANGED);
                intent.putExtra(Constants.KEY_AUDIO_SETTING, sp.getBoolean("isaudio", true));
                PushMessageActivity.this.sendBroadcast(intent);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
            }

        });
    }

    enum SettingMode {
        REPLY, PRIVATEMESSAGE, ATTENTION, SYSTEM, AUDIO
    }

    /**
     * 布尔型转int型
     * 
     * @param bol
     * @return
     */
    public String boolean2int(boolean bol) {
        String a = "0";
        boolean bTrue = bol;
        if (bTrue) {
            a = "1";
        } else {
            a = "0";
        }
        return a;
    }


}
